<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
		<link rel="stylesheet" type="text/css" href="css/element.css" />
		<link rel="stylesheet" type="text/css" href="css/reset.css" />
		<link rel="stylesheet" type="text/css" href="css/pageCss.css" />
		<link rel="stylesheet" type="text/css" href="css/common.css" />
		<script src="js/jquery-3.5.1.js"></script>
		<script src="js/vue.js" type="text/javascript" charset="utf-8"></script>
		<script src="js/element.js" type="text/javascript" charset="utf-8"></script>
		<script src="js/appmain.js" type="text/javascript" charset="utf-8"></script>
	</head>
	<body>
		<div id="app">

			<div id="head">
				<div class="h_title">
					<span style="color: #67C23A">种子扦样数据系统</span>
					<el-divider direction="vertical"></el-divider>
					<i :class="isCollapse ? 'el-icon-s-unfold':'el-icon-s-fold'"  @click="isCollapse=!isCollapse"></i>
				</div>
				<div class="menu">
                    <el-dropdown @command="printerClick" @visible-change="printerVisible" style="margin-right: 20px">
						<span class="el-dropdown-link" style="color: #fff">
							<i class="el-icon-printer"></i> {{defaultPrinter}}
						</span>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item v-for="item in printers" :key="item" :command="item">{{item}}</el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>

					<el-dropdown @command="dropdownClick">
						<span class="el-dropdown-link" style="color: #fff">
							<i class="el-icon-s-help"></i> 工作台
						</span>
						<el-dropdown-menu slot="dropdown">
							<el-dropdown-item icon="el-icon-view" command="view">全部打印</el-dropdown-item>
                            <el-tooltip class="item" effect="dark" content="扦样单、现场记录、扦样照片、确认函" placement="left">
                                <el-dropdown-item icon="el-icon-view" command="quickview">现场打印</el-dropdown-item>
                            </el-tooltip>
							<el-dropdown-item icon="el-icon-files" command="save">保存</el-dropdown-item>
							<el-dropdown-item icon="el-icon-document" command="export">导出</el-dropdown-item>
							<el-dropdown-item icon="el-icon-switch-button" command="shutdown">退出</el-dropdown-item>
						</el-dropdown-menu>
					</el-dropdown>
				</div>
			</div>

			<div id="content">
				<div id="left">
					<div style="overflow-y: auto">
						<el-menu :default-active="menuIdx" class="left-menu" @select='menuClick' background-color="#545c64" text-color="#fff" active-text-color="#ffd04b"
								 editable @edit="handleTabsEdit" :collapse="isCollapse">
							<el-menu-item index="yp.html">
								<i class="el-icon-tickets"></i>
								<template #title>扦样单</template>
							</el-menu-item>
							<el-menu-item index="xcjl.html">
								<i class="el-icon-edit-outline"></i>
								<template #title>现场记录</template>
							</el-menu-item>
							<el-menu-item index="qczp.html">
								<i class="el-icon-picture-outline"></i>
								<template #title>扦样照片</template>
							</el-menu-item>
							<el-menu-item index="letter.html">
								<i class="el-icon-document-checked"></i>
								<template #title>确认函</template>
							</el-menu-item>
							<el-menu-item index="fy.html">
								<i class="el-icon-tickets"></i>
								<template #title>报告封面</template>
							</el-menu-item>
							<el-menu-item index="notes.html">
								<i class="el-icon-collection-tag"></i>
								<template #title>报告注意事项</template>
							</el-menu-item>
							<el-menu-item index="bg1.html">
								<i class="el-icon-document"></i>
								<template #title>报告第1页</template>
							</el-menu-item>
							<el-menu-item index="bg2.html">
								<i class="el-icon-document"></i>
								<template #title>报告第2页</template>
							</el-menu-item>
							<el-submenu index="1">
								<template slot="title">
									<i class="el-icon-menu"></i>
									<span>参数设定</span>
								</template>
								<el-menu-item index="siparam.html">净度容许误差</el-menu-item>
								<el-menu-item index="grparam.html">芽率容许误差</el-menu-item>
								<el-menu-item index="testparam.html">样品测试参数</el-menu-item>
								<el-menu-item index="empparam.html">人员列表</el-menu-item>
							</el-submenu>
                            <el-menu-item index="record.html">
                                <i class="el-icon-data-analysis"></i>
                                <template #title>历史数据</template>
                            </el-menu-item>
						</el-menu>
					</div>

				</div>

				<div id="right">
					<div  style="height: 100%;">
						<el-tabs v-model="ypItemActive" type="card" editable @edit="handleTabsEdit" v-show="flag">
							<el-tab-pane v-for="(item, i) in ypList" :label="item.title" :name='item.name' :key='i'>
							</el-tab-pane>
						</el-tabs>
						<iframe class="sub_page ifm" name="ifm" runat="server" :src="ifm1" width="100%" height="100%" frameborder="no"
								border="0" marginwidth="0" marginheight="0" scrolling="yes" allowtransparency="yes" v-if="flag && ypList.length>0 && menuIdx !=''"></iframe>
						<iframe class="sub_page2 ifm" name="ifm" runat="server" :src="menuIdx" width="100%" height="100%" frameborder="no"
								border="0" marginwidth="0" marginheight="0" scrolling="yes" allowtransparency="yes"  v-if="!flag"></iframe>
					</div>
				</div>
			</div>
            <div class="printBtn" v-show="pbtnShow">
                <el-tooltip class="item" effect="dark" content="打印当前页" placement="left">
                    <el-button type="primary" icon="el-icon-printer" circle @click="printOne"></el-button>
                </el-tooltip>
            </div>

            <el-dialog title="保存数据" :visible.sync="dialog1" width="40%" label-width="100px">
                <el-form :model="record">
                    <el-form-item label="受检单位:">
                        <el-input v-model="record.company" placeholder="建议以“日期-受检单位名”的格式，例如：20210121-某某种子店"></el-input>
                    </el-form-item>
                    <el-form-item label="地址:">
                        <el-input v-model="record.address"></el-input>
                    </el-form-item>
                </el-form>
                <div slot="footer" class="dialog-footer">
                    <el-button @click="dialog1 = false">取 消</el-button>
                    <el-button type="primary" @click="dialog1Sure">确 定</el-button>
                </div>
            </el-dialog>


		</div>
		<style>
			.el-tabs__header {
				padding: 0;
				position: relative;
				margin: 0 30px 15px 30px;
			}
			.left-menu:not(.el-menu--collapse) {
				width: 200px;
			}
		</style>
		<script type="text/javascript">
			(function() {
				setRightHeight()
			})()

			window.onresize = function() {
				setRightHeight()
			}

			function setRightHeight() {
				$('#content #left').css('height', $(window).height() - 60)
				$('#content #right').css('height', $(window).height() - 60)
                var ifm = $('#content .sub_page')
                var ifm2 = $('#content .sub_page2')
                if(ifm) ifm.css('height', $(window).height() - 60 - 70)
                if (ifm2) ifm2.css('height', $(window).height() - 60)
			}
		</script>
		<script>
			index = new Vue({
				el: '#app',
				data: {
					isCollapse:false,
					// 左侧菜单标识
					menuIdx: '',
					tabIdx:'0',
					// 样品集合
					ypItemActive: '1',
					flag:true,
                    pbtnShow:false,
					ypList: [],
					printers: [],
                    defaultPrinter:'打印机',
                    record:{company:'',address:''},
                    dialog1:false
				},
                computed: {
                    // 计算属性的 getter
                    ifm1: function () {
                        // `this` 指向 vm 实例 menuIdx+'?index='+ypItemActive
                        return this.menuIdx + '?index=' + this.ypItemActive
                    }
                },
				created() {
					this.getYpSize()
					this.getSiParam()
					this.getGrParam()
					this.getTestParam()
					this.getEmployee()
					this.getPrinter()
				},
				methods: {
					// 左侧菜单点击
					menuClick(index) {
						this.menuIdx = index
                        this.pbtnShow = ['qczp.html','xcjl.html','yp.html','letter.html'].includes(index) && this.ypList.length>0
						if(['qczp.html','xcjl.html','siparam.html','grparam.html','testparam.html','empparam.html','record.html'].includes(index)){
							this.flag=false
                        }else{
							this.flag=true
						}
						setRightHeight()
					},
					// tab监听
					handleTabsEdit(targetName, action) {
						if (action === 'add') {
							this.addTab(true);
						} else if (action === 'remove') {
							var tabs = this.ypList;
							var activeName = this.ypItemActive;
							tabs.splice(parseInt(targetName) - 1, 1);
                            this.delYp(activeName-1);

                            var arr = []
							tabs.forEach(function (item, index) {
								var idx = index + 1
								arr.push({
									title: '样品' + idx,
									name: idx + ''
								})
							})
							activeName = arr.length + ''
							this.ypItemActive = activeName;
							this.ypList = arr;
						}
                        this.pbtnShow = ['qczp.html','xcjl.html','yp.html','letter.html'].includes(this.menuIdx) && this.ypList.length>0
                    },
                    addTab(flag){
                        var count = this.ypList.length + 1;

                        if (count > 6) {
                            this.$message({
                                title: '警告',
                                message: '最多只能添加6个样品数据',
                                type: 'warning',
                                duration: 1500

                            });
                            return;
                        }

                        this.ypList.push({
                            title: '样品' + count,
                            name: count + ''
                        });
                        if(count == 1){
                            this.ypItemActive = count + '';
                            setRightHeight()
                        }
                        if(flag){
                            this.addYp()
                        }
                    },

					dropdownClick(val){
						if(val == 'view'){
                            if(this.checkSapmleData()){
                                this.viewPrint(1)
                            }
						}else if(val == 'quickview'){
                            if(this.checkSapmleData()){
                                this.viewPrint(2)
                            }
                        } else if(val == 'export'){
						    if(this.checkSapmleData()){
                                this.export()
                            }
						} else if(val == 'shutdown'){
                            this.shutdown()
                        } else if(val == 'save'){
                            this.save()
                        }
                    },
                    printerClick(val){
					    this.defaultPrinter = val
                        window.cache.printer = val
                    },
                    // 退出
                    shutdown(){
					    var that = this
                        this.$confirm('确认退出?', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            type: 'warning'
                        }).then(() => {
                            $.get("http://localhost/sys/shutdown")
                            that.closePage()
                        }).catch(() => {});
                    },

                    closePage() {
                        if (navigator.userAgent.indexOf("Firefox") != -1 || navigator.userAgent.indexOf("Chrome") !=-1) {
                            window.location.href="about:blank";
                            window.close();
                        } else {
                            window.opener = null;
                            window.open("", "_self");
                            window.close();
                        }
                    },
                    printerVisible(val){
					    if(val){
					        this.getPrinter()
                        }
                    },

                    // ************保存*****************
                    save(){
					    if(this.record.id>0){
					        this.doSave();
                        }else{
                            this.dialog1 = true
                        }
                    },
                    doSave(){
					    var that = this
                        var pageData = window.cache.getData()
                        var formData = new FormData();
                        pageData.picArr.forEach(item => {
                            formData.append("files",item)
                        })
                        $.ajax({
                            url:"http://localhost/data/uploadPic",
                            type:"post",
                            contentType:false,
                            data:formData,
                            processData:false,
                            success: function (res) {
                                var param = {
                                    samples: pageData.sampleArr,
                                    fys: pageData.fyArr,
                                    bg1s: pageData.bg1Arr,
                                    bg2s: pageData.bg2Arr,
                                    notices: pageData.noticeArr,
                                    letters: pageData.letterArr,
                                    xcjl: pageData.xcjl,
                                    qczp: res.data
                                }
                                $.ajax({
                                    url:"http://localhost/data/save?recordId=" + that.record.id,
                                    type:"post",
                                    contentType: "application/json",
                                    dataType:"json",
                                    data:JSON.stringify(param),
                                    success: function (data) {
                                        that.$message({message: '保存成功',type:'success'});
                                        that.dialog1 = false
                                    }, error: function () {
                                        that.$message({message: '保存失败',type: 'warning'});
                                    }
                                })
                            }, error: function () {
                                console.log("上传失败！");
                            }
                        })
                    },
                    saveRecord(){
					    var that = this
                        if(window.cache.sampleArr.length == 0){
                            that.$message({message: '未添加样品数据',type: 'warning'});
                            return;
                        }

					    $.post('http://localhost/record/addRecord',this.record,function (res) {
                            if(res.code == 0){
                                that.record = res.data
                                that.doSave();
                            }else{
                                that.$message({message: '受检单位名称已存在',type: 'warning'});
                            }
                        })
                    },
                    dialog1Cancel(){
					    this.record.address=''
					    this.record.company=''
                        dialog1 = false
                    },
                    dialog1Sure(){
					    if(this.record.company.trim().length == 0){
                            this.$message({message: '受检单位不能为空',type: 'warning'});
                        }else{
                            this.saveRecord()
                        }
                    },
					/*********************************************/
					getRecordData(){
					    var that = this;
                        this.menuIdx = 'yp.html';
                        this.ypList = [];
                        this.tabIdx = "0";
                        this.ypItemActive = "0";
                        this.flag = true;
                        this.menuClick('yp.html')

					    $.get("http://localhost/data/getRecord?recordId=" + this.record.id,function (res) {
							console.log(res);
							console.log(window);
							debugger
							var data = res.data;
                            window.cache.reset();
                            var samples = data.samples;
                            samples.forEach(item => {
                                item.bzActive = item.bzActive == 'true';
                                item.sealed = item.sealed == 'true';
                                item.gmo = item.gmo == 'true';
                                item.chemical = item.chemical == '有：';
                            })
                            window.cache.sampleArr = data.samples;
                            window.cache.letterArr = data.letters;
                            window.cache.noticeArr = data.notices;
                            window.cache.fyArr = data.fys;
                            window.cache.bg1Arr = data.bg1s;
                            window.cache.bg2Arr = data.bg2s;
                            window.cache.xcjl = data.xcjl;
                            var qczp = window.cache.createQczp();
                            data.qczp.forEach(item => {
                                var idx = item.idx;
                                qczp[idx].title = item.title
                                qczp[idx].file = that.dataURLtoFile('data:image/png;base64,' + item.imgData, idx +'.png')
                            })
                            window.cache.qczp = qczp

                            var len = data.samples.length;
                            for (var i = 0; i < len; i++) {
                                that.addTab(false)
                            }
                        })
					},
                    dataURLtoFile(dataurl, filename) {
                        var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
                            bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
                        while(n--){
                            u8arr[n] = bstr.charCodeAt(n);
                        }
                        return new File([u8arr], filename, {type:mime});
                    },
                    getPrinter(){
                        var that = this
                        $.get("http://localhost/sys/getPrinter",function(res){
                            window.cache.printer = res.data.default
                            that.defaultPrinter = res.data.default
                            that.printers = res.data.list
                        })
                    },

					getYpSize(){
						var size = window.cache.getYpSize();
						var arr = []
						for (var i = 0; i < size; i++) {
							arr.push({
								title:'样品' + (i+1),
								name:(i+1) + ''
							})			
						}
						this.ypList = arr
					}
					,
					addYp(){
						window.cache.addYp();
					},
					
					delYp(delIdx){
						window.cache.delYp(delIdx);
					},
					// 获取净度参数
					getSiParam(){
						$.get("http://localhost/sys/getSiParam",function(res){
							window.cache.siParam = res.data
						})
					},
					// 获取发芽率参数
					getGrParam(){
						$.get("http://localhost/sys/getGrParam",function(res){
							window.cache.grParam = res.data
						})
					},
					// 获取检验参数
					getTestParam(){
						$.get("http://localhost/sys/getTestParam",function(res){
							window.cache.testParam = res.data
						})
					},
					// 获人员
					getEmployee(){
						$.get("http://localhost/sys/getEmployee",function(res){
						    var arr = []
                            res.data.forEach(function (item) {
                                arr.push(item.c0)
                            })
							window.cache.employee = arr
						})
					},

                    // 预览打印
                    viewPrint(type){
                        this.openLoading()
                        var pageData = window.cache.getData()
                        var formData = new FormData();
                        pageData.picArr.forEach(item => {
                            formData.append("files",item)
                        })
                        var that = this

                        $.ajax({
                            url:"http://localhost/data/uploadPic",
                            type:"post",
                            contentType:false,
                            data:formData,
                            processData:false,
                            success: function (res) {
                                var param = {
                                    samples: pageData.sampleArr,
                                    letters: pageData.letterArr,
                                    xcjl: pageData.xcjl,
                                    qczp: res.data,
                                    excludeInfoTable: 1 // 不要样品信息表
                                }
                                if(type == 1){ // 打印全部
                                    param.fys = pageData.fyArr;
                                    param.bg1s = pageData.bg1Arr;
                                    param.bg2s = pageData.bg2Arr;
                                    param.notices = pageData.noticeArr;
                                }
                                that.exportData(param,1)
                            }, error: function () {
                                console.log("上传失败！");
                            }
                        })
                    },

                    // 导出
                    export(){
					    this.openLoading()
						var pageData = window.cache.getData()
						var formData = new FormData();
                        pageData.picArr.forEach(item => {
                            formData.append("files",item)
                        })
                        var that = this

                        this.$prompt('请输入导出文件名', '提示', {
                            confirmButtonText: '确定',
                            cancelButtonText: '取消',
                            inputPattern: /\S/,
                            inputErrorMessage: '文件名不能为空'
                        }).then(({ value }) => {
                            $.ajax({
                                url:"http://localhost/data/uploadPic",
                                type:"post",
                                contentType:false,
                                data:formData,
                                processData:false,
                                success: function (res) {
                                    var param = {
                                        samples: pageData.sampleArr,
                                        fys: pageData.fyArr,
                                        bg1s: pageData.bg1Arr,
                                        bg2s: pageData.bg2Arr,
                                        notices: pageData.noticeArr,
                                        letters: pageData.letterArr,
                                        xcjl: pageData.xcjl,
                                        qczp: res.data
                                    }
                                    that.exportData(param,2,value)
                                }, error: function () {
                                    console.log("上传失败！");
                                }
                            })
                        }).catch(() => {
                            that.loading.close()
                        });
					},

                    exportData(param,type,fileName){
                        var that = this
                        $.ajax({
                            url:"http://localhost/data/export",
                            type:"post",
                            contentType: "application/json",
                            dataType:"json",
                            data:JSON.stringify(param),
                            success: function (data) {
                                console.log("成功!!!!");
                                if(type == 1){
                                    that.printOnline()
                                } else {
                                    that.downloadFile('http://localhost/data/download?fileName=' + fileName)
                                }
                                that.loading.close()
                            }, error: function () {
                                console.log("失败！");
                                that.loading.close()
                            }
                        })

                    },
                    downloadFile(url) {
                        //下载文件
                        var a = document.createElement("a");
                        a.setAttribute("href", url);
                        var clickEvent = document.createEvent("MouseEvents");
                        clickEvent.initEvent("click", true, true);
                        a.dispatchEvent(clickEvent);
                    },
                    printOnline(){
					    var that = this
                        this.$notify.info({
                            title: '消息',
                            message: '打印开始'
                        });
					    $.get("http://localhost/data/print?printerName=" + that.defaultPrinter,function () {
                        })
                    },
                    openLoading() {
                        this.loading = this.$loading({
                            lock: true,
                            text: '数据处理中，耐心等待...',
                            spinner: 'el-icon-loading',
                            background: 'rgba(0, 0, 0, 0.7)'
                        });

                    },
                    // 校验数据是否完整
                    checkSapmleData() {
                        var arr = window.cache.sampleArr;
                        var result = true;
                        if(arr.length == 0){
                            this.$alert('为添加扦样数据！', '提示', {
                                confirmButtonText: '确定',
                            });
                            result = false;
                        }

                        for (var i = 0; i < arr.length; i++) {
                            var item = arr[i];
                            for (var key in item){
                                if(!['chemicalMsg','bzActive','sealed','gmo','chemical'].includes(key) && !item[key]){
                                    result = false;
                                    this.$alert('扦样单'+(i+1)+'有数据未填！', '提示', {
                                        confirmButtonText: '确定',
                                    });
                                    break;
                                }
                            }
                            if(!result){
                                break
                            }
                        }

                        return result;
					},
                    // 打印某一页
                    printOne(){
                        debugger
                        console.log(this.menuIdx,this.ypItemActive)
                        var that = this
                        var type = 0;
                        this.openLoading()
                        var pageData = window.cache.getData()

                        var param = {}

                        if(this.menuIdx == 'yp.html'){
                            param.samples = [pageData.sampleArr[this.ypItemActive - 1]]
                            type = 1;
                        }else if(this.menuIdx == 'letter.html'){
                            param.letters = [pageData.letterArr[this.ypItemActive - 1]]
                            type = 3;
                        } else if(this.menuIdx == 'qczp.html'){
                            type = 4;
                        } else if(this.menuIdx == 'xcjl.html'){
                            param.xcjl = pageData.xcjl
                            type = 2;
                        }

                        if(this.menuIdx == 'qczp.html'){
                            var formData = new FormData();
                            pageData.picArr.forEach(item => {
                                formData.append("files",item)
                            })

                            $.ajax({
                                url:"http://localhost/data/uploadPic",
                                type:"post",
                                contentType:false,
                                data:formData,
                                processData:false,
                                success: function (res) {
                                    var param = {xcjl: pageData.xcjl,qczp: res.data}

                                    $.ajax({
                                        url:"http://localhost/data/export?type=" + type,
                                        type:"post",
                                        contentType: "application/json",
                                        dataType:"json",
                                        data:JSON.stringify(param),
                                        success: function (data) {
                                            console.log("成功!!!!");
                                            that.printOnline()
                                            that.loading.close()
                                        }, error: function () {
                                            console.log("失败！");
                                            that.loading.close()
                                        }
                                    })
                                }, error: function () {
                                    console.log("上传失败！");
                                }
                            })
                        }else{
                            $.ajax({
                                url:"http://localhost/data/export?type=" + type,
                                type:"post",
                                contentType: "application/json",
                                dataType:"json",
                                data:JSON.stringify(param),
                                success: function (data) {
                                    console.log("成功!!!!");
                                    that.printOnline()
                                    that.loading.close()
                                }, error: function () {
                                    console.log("失败！");
                                    that.loading.close()
                                }
                            })
                        }
                    }
				}
			})
		</script>
	</body>
</html>
